package com.codi.bus.core.service.impl;

import com.codi.base.util.MD5;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.BankNameDao;
import com.codi.bus.core.dao.LookupDao;
import com.codi.bus.core.dao.UserBankDao;
import com.codi.bus.core.domain.BankName;
import com.codi.bus.core.domain.Lookup;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.domain.UserBank;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.core.service.BankService;
import com.codi.bus.core.service.BranchBankService;
import com.codi.bus.core.service.UserService;
import com.codi.fcloud.ufx.HsResponseUtil;
import com.codi.fcloud.ufx.constant.HSOutputParameterNames;
import com.codi.fcloud.ufx.hssale.query.AccountBankQuery;
import com.codi.message.constant.ErrorConstant;
import com.codi.trade.dto.BankinfoModAcctDto;
import com.codi.trade.dto.HsAccoBankQueryDto;
import com.codi.trade.response.HsAccoBankQueryResponse;
import com.codi.trade.service.BankinfoModAcctService;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2018/2/28.
 */
@Service("branchBankService")
@Transactional
public class BranchBankServiceImpl implements BranchBankService {
    private static final Logger logger = LoggerFactory.getLogger(BranchBankServiceImpl.class);
    @Autowired
    private BankNameDao bankNameDao;

    @Autowired
    private LookupDao lookupDao;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountBankQuery accountBankQuery;

    @Autowired
    private BankService bankService;

    @Autowired
    private BankinfoModAcctService bankinfoModAcctService;

    @Autowired
    private UserBankDao userBankDao;

    @Override
    public List<String> getProvince(){
        List<String> provinces = bankNameDao.selectProvince();
        return provinces;
    }

    @Override
    public List<String> getCity(String provinceName){
        List<String> city = bankNameDao.selectCity(provinceName);
        return city;
    }

    @Override
    public List<BankName> getCityBank(String cityName, String bankName){
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);
        String bankNo = "";
        for (Lookup lookup : lookups){
            if (bankName.equals(lookup.getRuleText())){
                bankNo = lookup.getRuleValue();
                break;
            }
        }
        List<BankName> cityBank = bankNameDao.selectByCityAndBank(cityName,bankNo);
        return cityBank;
    }

    @Override
    public List<BankName> getFundBank(String bankName, String word){
        List<Lookup> lookups = lookupDao.getLookupByType(RuleConstant.RULE_LOOKUP_TYPE_HSBANK);
        String bankNo = "";
        for (Lookup lookup : lookups){
            if (bankName.equals(lookup.getRuleText())){
                bankNo = lookup.getRuleValue();
                break;
            }
        }
        List<BankName> fundBank = bankNameDao.selectByWord(bankNo,word);
        return fundBank;
    }

    @Override
    public BaseResult setBranchBank(Long userId, String vcBranchbank, String vcBankname, String tradePassword){
        BaseResult result = new BaseResult();
        User user = userService.getUser(userId);
        if (Strings.isNullOrEmpty(user.getExternalClientId())) {
            return result;
        }
        HsAccoBankQueryDto queryDto = HsAccoBankQueryDto.builder()
            .client_id(user.getExternalClientId())
            .build();

        List<HsAccoBankQueryResponse> hsBanks = accountBankQuery.query(queryDto);
        String bankNo = bankNameDao.selectBankNo(vcBranchbank);
        if (hsBanks == null){
            result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
            result.setSuccess(false);
            result.setErrorCode(ErrorConstant.ERROR_NO_BANK_CARD_FIND);
            result.setErrorMessage("没有相应银行卡信息");
            return result;
        }
        for (HsAccoBankQueryResponse hsbank : hsBanks){
            logger.debug("嘿嘿");
            if (hsbank.getBank_no().equals(bankNo) && !hsbank.getTrade_acco().startsWith("ZH") && !"1".equals(hsbank.getCapital_mode())){
                logger.debug("哈哈");
                List<UserBank> userBanks = bankService.getBanksNew(user.getUserId(), hsbank.getBank_account(), hsbank.getCapital_mode());
                UserBank userBank = new UserBank();
                if (userBanks == null || userBanks.isEmpty()) {
                    result.setSuccess(false);
                    result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
                    result.setErrorCode(ErrorConstant.ERROR_NO_BANK_CARD_FIND);
                    result.setErrorMessage("没有相应银行卡信息");
                    return result;
                }else {
                    userBank = userBanks.get(0);
                }

                //如果银行卡支行信息已经存在
                if (userBank.getBranchbank() != null && userBank.getBranchbank().equals(vcBranchbank)){
                    continue;
                }

                BankinfoModAcctDto bankinfoModAcctDto = BankinfoModAcctDto.builder()
                    .password(MD5.MD5Encode(tradePassword))
                    .bank_no(hsbank.getBank_no())
                    .bank_name(vcBankname)
                    .bank_account_name(hsbank.getBank_account_name())
                    .bank_account(hsbank.getBank_account())
                    .capital_mode(hsbank.getCapital_mode())
                    .original_bank_no(hsbank.getBank_no())
                    .original_bank_account(hsbank.getBank_account())
                    .branchbank(vcBranchbank)
                    .remittance_no(hsbank.getRemittance_no())
                    .bank_open_id_kind_gb(hsbank.getBank_open_id_kind_gb())
                    .bank_open_id_no(hsbank.getBank_open_id_no())
                    .original_fund_way(hsbank.getCapital_mode())
                    .detail_fund_way(hsbank.getDetail_fund_way())
                    .fund_card(hsbank.getFund_card())
                    .fund_interface_type(hsbank.getFund_interface_type())
                    .trade_acco(hsbank.getTrade_acco())
                    .build();


                Map<String, Object> map = bankinfoModAcctService.modAcct(bankinfoModAcctDto);
                if (!HsResponseUtil.isOperationOk(map)) {
                    String errorInfo = map.get(HSOutputParameterNames.ERROR_INFO).toString();
                    result.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
                    result.setSuccess(false);
                    result.setErrorCode(ErrorConstant.ERROR_HUNDSUNAPI_WRONG);
                    result.setErrorMessage(errorInfo);
                } else {
                    userBank.setBranchbank(vcBranchbank);
                    userBank.setBankBranchName(vcBankname);
                    userBankDao.update(userBank);
                }
            }
        }
        return result;
    }



}
